package org.domeos.configuration;

import javax.sql.DataSource;

import org.domeos.global.GlobalConstant;
import org.domeos.util.DatabaseType;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.taobao.tddl.group.jdbc.TGroupDataSource;

/**
 * Created by feiliu206363 on 2017/3/27.
 */
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = "org.domeos.framework.api.mapper.portal", sqlSessionFactoryRef = "portalSqlSessionFactory")
public class PortalConfiguration {
	
	@Value("${portal.mysql.dbGroupKey}")
	private String dbGroupKey;
	
	@Value("${portal.mysql.appName}")
	private String appName;
	
    @Bean(initMethod = "init", name = "portalDataSource")
    public DataSource portalDataSource() throws Exception {
    	TGroupDataSource dataSource = new TGroupDataSource(dbGroupKey, appName);
        return dataSource;
    }

    @Bean(name = "portalTransactionManager")
    public DataSourceTransactionManager portalTransactionManager() throws Exception {
        return new DataSourceTransactionManager(portalDataSource());
    }

    @Bean(name = "portalSqlSessionFactory")
    public SqlSessionFactoryBean sqlSessionFactory(@Qualifier("portalDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        GlobalConstant.DATABASETYPE = DatabaseType.MYSQL;
        return sessionFactory;
    }
}
